package dk.itu.samd.group2.tagapastry;

import java.util.Vector;

public final class Merger {

	// Private constructor to ensure the class cant be instantiated
	private Merger() {}
	
	// Merges two sorted vectors by rank
	public static Vector<IndexEntry> merge(Vector<IndexEntry> vec1, Vector<IndexEntry> vec2) {
		
		
		if (vec1.size() == 0) {
			return vec2;
		} else if (vec2.size() == 0) {
			return vec1;
		}

		Vector<IndexEntry> merged = new Vector<IndexEntry>(vec1.size() + vec2.size());

		int index1 = 0, index2 = 0;

		for (int i = 0; i < merged.capacity(); i++) {
			IndexEntry from1 = vec1.get(index1);
			IndexEntry from2 = vec2.get(index2);

			if (from1.getRank() > from2.getRank()) {
				
				if(vec1.size() == 1) {
					merged.add(from1);
					addRest(index2,merged,vec2);
					return merged;
				}
				
				merged.add(from1);
				if (index1 != vec1.size() - 1) {
					index1++;
				}
			} else {
				
				// If there is only one element, then put it on top
				// of the list and append others, finally quit
				if(vec2.size() == 1) {
					merged.add(from2);
					addRest(index1,merged,vec1);
					return merged;
				}
				
				merged.add(from2);
				if (index2 != vec2.size() - 1) {
					index2++;
				}
			}
		}

		return merged;		
	}
	
	private static void addRest(int start, Vector<IndexEntry> merged, Vector<IndexEntry> toAdd) {
		for(int i=start; i < toAdd.size(); i++)
			merged.add(toAdd.get(i));
	}
	
}
